<?
/**
 *账单类.
 *调用getbill()生成供应商和下属分销商的账单,作为对照数据.
 */
class Bill{
    /**
	 *分销商id
	 *@var int
	 */
	private $fid;
	
	 /**
	 *供应商id
	 *@var int
	 */
	private $aid;
	
	 /**
	 *出账配置,键值数组
	 *@var array
	 */
	private $configs;
	
	/**
	 *票付通内部接口对象
	 *@var object
	 */
	private $s;
	
	/**
	 *数据库对象
	 *@var object
	 */
	private $data;
	
	/**
	 *构造函数.
	 *初始化内部变量.
	 *@param int $fid 分销商id
	 *@param int $aid 供应商id
	 *@param object $s 票付通内部接口对象
	 *@param object $data 数据库对象
	 */
	public function __construct($fid,$aid,$s,$data){
		$this->aid=$aid;
		$this->fid=$fid;
		$this->s=$s;
		$this->data=$data;
		$str="select `id`, `fid`, `aid`, `stype`, `status`, `billdate`,`smethod`,"
            ."`begintime` FROM uu_settle where fid=$fid and aid=$aid LIMIT 1";
		$this->data->query($str);
		$this->configs=$this->data->fetch_assoc();
	}
	
	/**
	 *生成账单函数.
	 *根据配置数据，产生对应的账单记录。
	 */
	public function getbill(){
		$configs=$this->configs;
		$begintime=$configs['begintime'];
		$billdate=$configs["billdate"];
		$smethod=$configs["smethod"];
		$aid=$this->aid;
		$fid=$this->fid;
		$str="select max(etime) as btime from uu_bill where aid=$aid and fid=$fid";
		$this->data->query($str);
		$this->data->fetch_assoc();
		$btime=$this->data->f('btime');
		$btime=($btime<=$begintime)?strtotime($begintime):(strtotime($btime)+1);
		$nowtime=time();
		$days=ceil(($nowtime-$btime)/24/3600);
		switch($smethod){
			case "2"://日结
					$limittime=time()-360*24*3600;//限制起始结算时间
					if($btime<=$limittime) return 0;
					$billdate=str_pad($billdate,2,"0",STR_PAD_LEFT);
					for($i=0;$i<$days;$i++){
						$btimeDate=date("Y-m-d H:i:s",$btime);
						$etime=$btime+24*3600;
						$etimeDate=date("Y-m-d $billdate:00:00",$etime);
						if($etimeDate>date("Y-m-d H:00:00")) break;
						$this->get($btimeDate,$etimeDate);
						$btime=strtotime($etimeDate)+1;//结束时间作为下一天起始时间
					}
				break;
			case "0"://月结
				if($days<14) break;//不满一个月跳出
				$sday=$billdate;
				for($i=0;$i<$days;$i++){
					$btimeDate=date("Y-m-d H:i:s",$btime);
					$year=date("Y",$btime);
					$month=date("n",$btime);
					$day=date("j",$btime);
					if($day<$sday){
						$etimeDate=$this->getEndDate($year,$month,$sday);
					}else{
						$month++;
						if($month==13){
							$month=1;
							$year++;
						}
						$etimeDate=$this->getEndDate($year,$month,$sday);
					}
					if($etimeDate>=date("Y-m-d")) break;
					$etimeDate=$etimeDate." 23:59:59";
					$this->get($btimeDate,$etimeDate);
					$btime=strtotime($etimeDate)+1;
				}
			break;
			case "1"://半月结
				$sday=$billdate;
				for($i=0;$i<$days;$i++){
					$btimeDate=date("Y-m-d H:i:s",$btime);
					$year=date("Y",$btime);
					$month=date("n",$btime);
					$day=date("j",$btime);
					if($day<$sday){
						$etimeDate=$this->getEndDate($year,$month,$sday);
					}else{
						$monthdays=date("t",$btime);
						$etimeDate=$year."-".str_pad($month,2,"0",STR_PAD_LEFT)."-".$monthdays;
					}
					if($etimeDate>=date("Y-m-d")) break;
					$etimeDate=$etimeDate." 23:59:59";
					$this->get($btimeDate,$etimeDate);
					$btime=strtotime($etimeDate)+1;
				}
			break;
			default:break;
		}
	}
	
	/**
	 *订单统计函数.
	 *调用接口，直接统计已完成,授信支付的订单。
	 *@param date $btimeDate 完成开始时间
	 *@param date $etimeDate 完成结束时间
	 *@return array  array(0=>总订单数,1=>总票数,2=>总金额)
	 */
	public function ordersCount($btimeDate,$etimeDate){
		$params=array(
						"btime3"=>$btimeDate,
						"etime3"=>$etimeDate,
						"status"=>"1|6",
						"pays"=>"0|1|2",
						"orderby"=>'',
						"sort"=>'',
						"rstart"=>0,
						"n"=>200,
						"c"=>0,
						"stype"=>0,
						"payinfo"=>"",
						"pmode"=>0,
						"remotenum"=>"",
						"origin"=>0,
						"p_type"=>"",
						"order_confirm"=>"",
						"concat"=>0,
						"aid"=>$this->aid,
						"mid"=>$this->fid,
						"ifpack"=>0);
		extract($params);
		$count=$this->s->Order_Globle_Search($sid,$mid,$lid,$tid,$ltitle,$ttitle,
            $btime1,$etime1,$btime2,$etime2,$btime3,$etime3,$ordernum,$oname,
            $otel,$status,$pays,$fromt,$orderby,$sort,$rstart,$n,0,$stype,
            $payinfo,$pmode,$remotenum,$origin,$p_type, $order_confirm,$aid,
            $concat,$ifpack);
        $x = simplexml_load_string($count);
        $order = 0;
        if($aid == $_SESSION['sid'])//应收
            foreach($x->Rec as $v){
                if((string)$v->UUaid==$_SESSION['sid'] && (int)$v->UUpmode==2)
                    ++$order;
                else{
                    if((string)$v->UUaids_money=='0') continue;
                    $UUaids_money = unserialize((string)$v->UUaids_money);
                    $UUaids = explode(',',(string)$v->UUaids);
                    $position = array_search($_SESSION['sid'],$UUaids);
                    foreach($UUaids_money as $row){
                        if($UUaids[$position+1]==$row[0] && $row[1]==0){
                            ++$order;
                            break;
                        }
                    }
                }
        }elseif($mid == $_SESSION['sid'])   //应付
            foreach($x->Rec as $v){
                if((string)$v->UUmid==$_SESSION['sid'] && (int)$v->UUpmode==2)
                    ++$order;
                else{
                    if((string)$v->UUaids_money=='0') continue;
                    $UUaids_money = unserialize((string)$v->UUaids_money);
                    $UUaids = explode(',',(string)$v->UUaids);
                    $position = array_search($_SESSION['sid'],$UUaids);
                    foreach($UUaids_money as $row){
                        if($UUaids[$position]==$row[0] && $row[1]==0){
                            ++$order;
                            break;
                        }
                    }
                }
            }
		return array($order,0,0);
	}
	
	/**
	 *订单统计明细函数.
	 *调用接口，返回传入时间段的simplexml数据记录。
	 *@param date $btimeDate 完成开始时间
	 *@param date $etimeDate 完成结束时间
	 *@return simplexml
	 */
	public function ordersDetail($btimeDate,$etimeDate){
		$params=array(
            "btime3"=>$btimeDate,
            "etime3"=>$etimeDate,
            "status"=>"1|6",
            "pays"=>"0|1|2",
            "orderby"=>1,
            "sort"=>1,
            "rstart"=>0,
            "n"=>9999999,
            "c"=>0,
            "stype"=>2,
            "payinfo"=>"2",
            "pmode"=>0,
            "remotenum"=>"",
            "origin"=>0,
            "p_type"=>"",
            "order_confirm"=>"",
            "concat"=>0,
            "aid"=>$this->aid,
            "mid"=>$this->fid,
            "ifpack"=>0);
		extract($params);
		$xml=$this->s->Order_Globle_Search($sid,$mid,$lid,$tid,$ltitle,$ttitle,$btime1,$etime1,$btime2,$etime2,$btime3,$etime3,$ordernum,$oname,$otel,$status,$pays,$fromt,$orderby,$sort,$rstart,$n,0,$stype,$payinfo,$pmode,$remotenum,$origin,$p_type, $order_confirm,$aid,$concat,$ifpack);
		return simplexml_load_string($xml);
	}
	
	/**
	 *账单记录函数.
	 *将指定时间段的账单记录记到数据库。
	 *@param date $btimeDate 完成开始时间
	 *@param date $etimeDate 完成结束时间
	 *@uses Bill::getbill()
	 */
	public function get($btimeDate,$etimeDate){

		$fid    = $this->fid;
		$aid    = $this->aid;
		$str    = "SELECT id FROM uu_bill WHERE fid=$fid AND aid=$aid AND btime='$btimeDate' AND etime='$etimeDate' LIMIT 1";
        $GLOBALS['le']->query($str);
		if(!$GLOBALS['le']->fetch_assoc()){//确保记录唯一
            $count  = $this->ordersCount($btimeDate,$etimeDate);
            $orders = $count[0];
            $tnums  = $count[1];
            $money  = $count[2];
			$str="insert uu_bill set fid=$fid,aid=$aid,btime='$btimeDate',etime='$etimeDate',orders=$orders,tnums=$tnums,money=$money,addtime=now()";
			$GLOBALS['le']->query($str);
		}
	}
	
	/**
	 *获得正确日期.
	 *如果设置的出账日期不存在如 2013-02-31
	 *就递归减小到正确日期.
	 *@param int year  年
	 *@param int month 月
	 *@param int day   日
	 *@return date
	 *@uses Bill::getbill
	 */
	public function getEndDate($year,$month,$day){
		if($month>12||$month<0||$day<0||$year<0) return false;
		if(checkdate($month,$day,$year)){
			return $year."-".str_pad($month,2,"0",STR_PAD_LEFT)."-".str_pad($day,2,"0",STR_PAD_LEFT);
		}else{
			return $this->getEndDate($year,$month,$day-1);
		}
	}
}
?>